package cn.lblbc.webbrowser.adapters

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import cn.lblbc.webbrowser.R
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import java.io.File

class SimpleBackgroundImageAdapter(
    private val context: Context,
    private val items: List<BackgroundImageItem>,
    private val currentSelection: String?,
    private val onItemClick: (BackgroundImageItem) -> Unit
) : RecyclerView.Adapter<SimpleBackgroundImageAdapter.ViewHolder>() {

    private var selectedPosition = items.indexOfFirst { item ->
        when {
            currentSelection == null && item.imagePath == null -> true
            currentSelection != null && item.imagePath == currentSelection -> true
            else -> false
        }
    }.also { position ->
        android.util.Log.d("SimpleBackgroundImageAdapter", "Initial selected position: $position, currentSelection: $currentSelection")
    }

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val previewImageView: ImageView = view.findViewById(R.id.previewImageView)
        val defaultIconImageView: ImageView = view.findViewById(R.id.defaultIconImageView)
        val selectedOverlay: View = view.findViewById(R.id.selectedOverlay)
        val selectedIcon: ImageView = view.findViewById(R.id.selectedIcon)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_background_image_simple, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = items[position]
        val isSelected = position == selectedPosition

        android.util.Log.d("SimpleBackgroundImageAdapter", "Binding item $position: ${item.imagePath}, selected: $isSelected")

        when (item.type) {
            BackgroundImageType.DEFAULT -> {
                // 显示默认背景图片原图
                holder.defaultIconImageView.visibility = View.GONE
                try {
                    val resourceId = context.resources.getIdentifier(
                        "bg", 
                        "drawable", 
                        context.packageName
                    )
                    android.util.Log.d("SimpleBackgroundImageAdapter", "Default bg resource ID: $resourceId")
                    if (resourceId != 0) {
                        Glide.with(context)
                            .load(resourceId)
                            .centerCrop()
                            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                            .into(holder.previewImageView)
                        
                        // 确保选中状态在图片加载后仍然可见
                        holder.previewImageView.post {
                            holder.selectedOverlay.visibility = if (isSelected) View.VISIBLE else View.GONE
                            holder.selectedIcon.visibility = if (isSelected) View.VISIBLE else View.GONE
                            holder.selectedOverlay.bringToFront()
                            holder.selectedIcon.bringToFront()
                        }
                    } else {
                        // 如果找不到默认背景图片，显示备用图标
                        holder.previewImageView.setImageDrawable(null)
                        holder.previewImageView.setBackgroundColor(
                            context.resources.getColor(android.R.color.darker_gray, null)
                        )
                        holder.defaultIconImageView.visibility = View.VISIBLE
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    holder.previewImageView.setImageDrawable(null)
                    holder.previewImageView.setBackgroundColor(
                        context.resources.getColor(android.R.color.darker_gray, null)
                    )
                    holder.defaultIconImageView.visibility = View.VISIBLE
                }
            }
            BackgroundImageType.BUNDLED -> {
                // 显示内置drawable资源
                holder.defaultIconImageView.visibility = View.GONE
                try {
                    val resourceId = context.resources.getIdentifier(
                        item.imagePath, 
                        "drawable", 
                        context.packageName
                    )
                    android.util.Log.d("SimpleBackgroundImageAdapter", "Resource ID for ${item.imagePath}: $resourceId")
                    if (resourceId != 0) {
                        Glide.with(context)
                            .load(resourceId)
                            .centerCrop()
                            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                            .into(holder.previewImageView)
                        
                        // 确保选中状态在图片加载后仍然可见
                        holder.previewImageView.post {
                            holder.selectedOverlay.visibility = if (isSelected) View.VISIBLE else View.GONE
                            holder.selectedIcon.visibility = if (isSelected) View.VISIBLE else View.GONE
                            holder.selectedOverlay.bringToFront()
                            holder.selectedIcon.bringToFront()
                        }
                    } else {
                        holder.previewImageView.setImageDrawable(null)
                        holder.previewImageView.setBackgroundColor(
                            context.resources.getColor(R.color.lighter_gray, null)
                        )
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                    holder.previewImageView.setImageDrawable(null)
                }
            }
            BackgroundImageType.COLLECTED, BackgroundImageType.CUSTOM -> {
                // 显示外部文件
                holder.defaultIconImageView.visibility = View.GONE
                val file = File(item.imagePath ?: "")
                if (file.exists()) {
                    Glide.with(context)
                        .load(file)
                        .centerCrop()
                        .diskCacheStrategy(DiskCacheStrategy.DATA)
                        .into(holder.previewImageView)
                    
                    // 确保选中状态在图片加载后仍然可见
                    holder.previewImageView.post {
                        holder.selectedOverlay.visibility = if (isSelected) View.VISIBLE else View.GONE
                        holder.selectedIcon.visibility = if (isSelected) View.VISIBLE else View.GONE
                        holder.selectedOverlay.bringToFront()
                        holder.selectedIcon.bringToFront()
                    }
                } else {
                    holder.previewImageView.setImageDrawable(null)
                }
            }
        }

        // 立即设置选中状态
        holder.selectedOverlay.visibility = if (isSelected) View.VISIBLE else View.GONE
        holder.selectedIcon.visibility = if (isSelected) View.VISIBLE else View.GONE
        
        // 确保选中状态的视图在最前面
        holder.selectedOverlay.bringToFront()
        holder.selectedIcon.bringToFront()

        holder.itemView.setOnClickListener {
            android.util.Log.d("SimpleBackgroundImageAdapter", "Item clicked: $position, ${item.imagePath}")
            val oldPosition = selectedPosition
            selectedPosition = position
            if (oldPosition != -1 && oldPosition < itemCount) {
                notifyItemChanged(oldPosition)
            }
            notifyItemChanged(selectedPosition)
            
            // 延迟一点时间再调用回调，让用户看到选中效果
            holder.itemView.postDelayed({
                onItemClick(item)
            }, 200)
        }
    }

    override fun getItemCount() = items.size
}